<?php

class ClientsController extends AppController
{

	public $name = 'Clients';
	public $helpers = array();
	public $uses = array('Client', 'Report');

	public $modelName = '';
	public $po_domain = '';
	public $url_part  = '';

	function beforeFilter()
	{
		parent::beforeFilter();

		$this->modelName = Inflector::singularize($this->name);
		$this->po_domain = Inflector::underscore($this->name);
		$this->url_part  = $this->po_domain;
		$this->set('po_domain', $this->po_domain);
		$this->set('url_part',  $this->url_part);
		$this->set('modelName', $this->modelName);
		$this->set('PKName',    $this->{$this->modelName}->primaryKey);
		Auth::Access('admin & active');
	}

	function create()
	{
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		if (!empty($this->data[$modelName]['submit_back'])) {
            $this->redirect("/{$url_part}/", null, true);
            exit();
	    }
		$this->set('mode', __FUNCTION__);
	    $this->pageTitle = strip_tags(__d($po_domain, 'create_title', true));

	    $submit = !empty($this->data);

	    if (!$this->{$modelName}->allowUpdate()) {
		    $this->data = array();
	    }
	    if (empty($this->data[$modelName]['tools'])) {
	        $this->data[$modelName]['tools'] = array();
	    }
		if ($this->{$modelName}->allowUpdate() && $submit) {
    		$admiting_fields = array_keys($this->{$modelName}->validate);
    		$this->data = ar::prepareBySchema($this->data, array($modelName => $admiting_fields));
			$error_msg = '';
			$success_msg = __d($po_domain, 'created', true);
			$id = null;
            if (empty($error_msg)) {
				if ($this->{$modelName}->save($this->{$modelName}->create($this->data))) {
       			    $id = $this->{$modelName}->getInsertID();
       			    $this->data[$modelName][$PKName] = $id;
				} elseif (!empty($this->{$modelName}->validationErrors)) {
					$error_msg = __d(null, 'Data are incorrectly entered.', true).' '.__d(null, 'Try again.', true);
				} else {
	    		    $error_msg = __d(null, 'There was an internal error.', true).' '.__d(null, 'Try later.', true);
				}
            }
			if (empty($error_msg)) {
			    $this->msgNotice($success_msg);
			    $this->redirect("/{$url_part}/{$id}/", null, true);
			    exit();
			} else {
			    $this->msgError($error_msg, @$error_code);
			}
		}

		$this->data[$modelName]['__allows']['update'] = $this->{$modelName}->allowUpdate();
		$this->data[$modelName]['__allows']['delete'] = $this->{$modelName}->allowDelete();
		$this->set('tools_list', $this->{$modelName}->getModel('Test')->generateList());

		$this->render('details');
	}

	function formForEntity(EntityForm $form)
	{

	}

	function list_of()
	{
		vendor('date');

	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		$this->pageTitle = strip_tags(__d($po_domain, 'list_title', true));

		vendor('contingencies');
		vendor('order_html');
		vendor('pagination_html');
		vendor('page_of_data');

		$contingencies = new Contingencies();
        $contingencies->model =& $this->{$modelName};
        $contingencies->expects = 'Tests';

        /////////////////////////////////////////////////////////////
        $ses_war_name = __CLASS__.':'.__FUNCTION__.'_filter';
        if (!empty($this->data['Filter'])) {
            if (!empty($this->data['Filter']['submit_reset'])) {
                unset($_SESSION[$ses_war_name]);
                unset($this->data['Filter']);
            } elseif (!empty($this->data['Filter']['submit_apply'])) {
                $_SESSION[$ses_war_name] = $this->data['Filter'];
            }
        }
        $filter = isset($_SESSION[$ses_war_name]) ? $_SESSION[$ses_war_name] : array();
        if (empty($this->data['Filter'])) {
            $this->data['Filter'] = $filter;
        }
        $this->set('filter', $filter);
        /////////////////////////////////////////////////////////////
		$conds = array();
        if (!empty($filter['searche'])) {
            $searche_fields = array(
            	"`{$modelName}`.`name`",
                "`{$modelName}`.`contract`",
                "`{$modelName}`.`reg_code`",
           		"`{$modelName}`.`contact_person_name`",
            	"`{$modelName}`.`contact_person_city`",
                "`{$modelName}`.`contact_person_tel`",
                "`{$modelName}`.`contact_person_email`",
            );
            $searche_fields_name = array(
                "name",
                "contract",
                "reg_code",
                "contact_person_name",
                "contact_person_city",
                "contact_person_tel",
                "contact_person_email",
            );
            $searche_params = array(
                'entirely'  => !empty($filter['searche_entirely']),
                'all'       => !empty($filter['searche_all']),
                'sequence'  => !empty($filter['searche_sequence']),
                'grouping'  => 'words', // chars
                'words'     => false,
            );
            $conds[] = $this->{$modelName}->searcheCond($filter['searche'], $searche_fields, $searche_params);
        }
		////////////////////////////////////////////////////////////////////////
        if (!empty($filter['status'])) {
            $conds[]["`{$modelName}`.`status`"] = $filter['status'];
        }
		if (!empty($filter['from_date']))
		{
			$conds[]["`{$modelName}`.`created`"] = ">={$filter['from_date']}";
		}
		if (!empty($filter['to_date']))
		{
			$conds[]["`{$modelName}`.`created`"] = "<=".Date::getToDateTime($filter['to_date']);
		}
		$contingencies->conditions =& $conds;
        //$contingencies->ns = __CLASS__.':'.__FUNCTION__;
		////////////////////////////////////////////////////////////////////////

        $appearence = new OrderHTML();
        $appearence->orderFields = array(
            $PKName => "`{$modelName}`.`{$PKName}`",
            'name' => "`{$modelName}`.`name`",
            'contract' => "`{$modelName}`.`contract`",
            'contract_start_date' => "`{$modelName}`.`contract_start_date`",
            'contract_finish_date' => "`{$modelName}`.`contract_finish_date`",
            'reg_code' => "`{$modelName}`.`reg_code`",
            'contact_person' => "`{$modelName}`.`contact_person_name`",
            'balance' => "`{$modelName}`.`balance`",
        );
        $appearence->defaultOrder = Order::parseString('name');
        $appearence->ns = __CLASS__.':'.__FUNCTION__;
        $appearence->processParams();

        $pagination = new PaginationHTML();
        $pagination->ns = __CLASS__.':'.__FUNCTION__;
        $pagination->defaultLimit = 20;
        $pagination->processParams();

        $list = new PageOfData($contingencies, $appearence, $pagination);

        foreach ($list->rows as &$row) {
            $row[$modelName]['__allows'] = array(
                'update' => $this->{$modelName}->allowUpdate($row[$modelName]),
                'delete' => $this->{$modelName}->allowDelete($row[$modelName]),
            );
            if (!empty($filter['searche'])) {
            	$this->{$modelName}->hightlightSearche($row[$modelName], $filter['searche'], $searche_fields_name, $searche_params);
            }
        }

		$this->set('list', $list);
		$this->set('tools_list', $this->{$modelName}->getModel('Test')->generateList());
	}

	function details($mode = 'details')
	{
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		if (!empty($this->data[$modelName]['submit_back'])) {
            $this->redirect("/{$url_part}/", null, true);
            exit();
	    }
		$this->set('mode', __FUNCTION__);
	    $this->pageTitle = strip_tags(__d($po_domain, 'details_title', true));

	    if (isset($this->params['id'])) {
	        $id = $this->params['id'];
	    }

	    $this->{$modelName}->rel('Tests');
        $tmp = $this->{$modelName}->read(null, $id);

		if (! is_array($tmp) || !count($tmp)) {
			$this->msgError(__d($po_domain, 'absent', true), @$error_code);
			$this->redirect("/{$url_part}/", null, true);
			exit();
		}

		$tmp[$modelName]['tools'] = array();
		foreach ($this->{$modelName}->getToolsFor($id) as $tool) {
		    $tmp[$modelName]['tools'][] = $tool['Test']['id'];
		}
		$admiting_fields = array_keys($this->{$modelName}->validate);

		////// MENU ///////////////////////

	    $this->MainMenu->setActive($this->MainMenu->findItem("/{$url_part}/"));

		///////////////////////////////////

		$submit = !empty($this->data);
		if (! $this->{$modelName}->allowUpdate($tmp[$modelName])) {
		    $this->data = array();
		}
		$this->data = ar::mergeBySchema($tmp, $this->data, array($modelName => $admiting_fields));

		if ($this->{$modelName}->allowUpdate($tmp[$modelName]) && $submit) {
		    if (empty($this->data[$modelName]['tools'])) {
		        $this->data[$modelName]['tools'] = array();
		    }
			$error_msg = '';
			$success_msg = __d($po_domain, 'changed', true);
            if (empty($error_msg)) {

				if ($this->{$modelName}->save($this->data)) {

				} elseif (!empty($this->{$modelName}->validationErrors)) {
					$error_msg = __d(null, 'Data are incorrectly entered.', true).' '.__d(null, 'Try again.', true);
				} else {
	    		    $error_msg = __d(null, 'There was an internal error.', true).' '.__d(null, 'Try later.', true);
				}
            }
			if (empty($error_msg)) {
			    $this->msgNotice($success_msg);
			    //$this->redirect("/{$url_part}/{$id}/", null, true);
			    $this->redirect("/{$url_part}/", null, true);
			    exit();
			} else {
			    $this->msgError($error_msg, @$error_code);
			}
		}

		$this->data[$modelName]['__allows']['update'] = $this->{$modelName}->allowUpdate($tmp[$modelName]);
		$this->data[$modelName]['__allows']['delete'] = $this->{$modelName}->allowDelete($tmp[$modelName]);
		$this->set('tools_list', $this->{$modelName}->getModel('Test')->generateList());
	}

	function remove($id = null)
	{
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

	    if (isset($this->params['id'])) {
	        $id = $this->params['id'];
	    }
		if (!$id) {
			$this->msgError(__d($po_domain, 'absent', true), @$error_code);
		} else {
            $this->{$modelName}->rel();
		    $data = $this->{$modelName}->read(null, $id);
		    if (is_array($data) && count($data)) {
		    	if ($this->{$modelName}->allowDelete($data[$modelName])) {
	    		    if ($this->{$modelName}->del($id)) {
	    	       		$this->msgNotice(__d($po_domain, 'deleted', true));
	        		} else {

	        		}
		    	} else {
			        $this->msgError(__d(null, 'deny', true), @$error_code);
		    	}
		    } else {
		        $this->msgError(__d($po_domain, 'absent', true), @$error_code);
		    }
		}
		$this->redirect("/{$url_part}/", null, true);
		exit();
	}

	function refill_account()
	{
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		if (!empty($this->data[$modelName]['submit_back'])) {
            $this->redirect("/{$url_part}/", null, true);
            exit();
	    }
		$this->set('mode', __FUNCTION__);
	    $this->pageTitle = strip_tags(__d($po_domain, 'refill_account_title', true));

	    if (isset($this->params['id'])) {
	        $id = $this->params['id'];
	    }

	    $this->{$modelName}->rel();
        $tmp = $this->{$modelName}->read(null, $id);

		if (! is_array($tmp) || !count($tmp)) {
			$this->msgError(__d($po_domain, 'absent', true), @$error_code);
			$this->redirect("/{$url_part}/", null, true);
			exit();
		}

		/* @var $this->Report Report */
	    $this->Report->generateList();

	    $FormRefill =& $this->{$modelName}->getModel('FormRefill'); /* @var $FormRefill FormRefill */
	    $Operation =& $this->{$modelName}->getModel('Operation'); /* @var $Operation Operation */
		$admiting_fields = array_keys($FormRefill->validate);

		////// MENU ///////////////////////

	    $ancestors_menu =& $this->MainMenu->findItem("/{$url_part}/");
	    $this->MainMenu->setActive($ancestors_menu);

		///////////////////////////////////

		$submit = !empty($this->data);
		if (! $this->{$modelName}->allowUpdate($tmp[$modelName])) {
		    $this->data = array();
		}
		$this->data = ar::mergeBySchema($tmp, $this->data, array($modelName => $admiting_fields));

		if ($this->{$modelName}->allowUpdate($tmp[$modelName]) && $submit) {
		    $this->data['FormRefill'] = $this->data[$modelName];
		    $FormRefill->data = $this->data;
		    $errors = $FormRefill->invalidFields();
			$error_msg = '';
			$success_msg = __d($po_domain, 'refilled', true);
            if (empty($error_msg)) {
				if (!count($errors)) {
                    $refill_data = $FormRefill->data['FormRefill'];
                    try {
                        $refill_domain = new DomainBill($refill_data['amount'], $refill_data['bill']);
                        $Operation->refill_account($refill_domain, $this->data);
                    } catch (Exception $e) {
                        $errors[] = 1;
                    }
                }
				if (!count($errors)) {
				} elseif (!empty($FormRefill->validationErrors)) {
					$error_msg = __d(null, 'Data are incorrectly entered.', true).' '.__d(null, 'Try again.', true);
				} else {
	    		    $error_msg = __d(null, 'There was an internal error.', true).' '.__d(null, 'Try later.', true);
				}
            }
			if (empty($error_msg)) {
			    $this->msgNotice($success_msg);
			    $this->redirect("/{$url_part}/", null, true);
			    exit();
			} else {
			    $this->msgError($error_msg, @$error_code);
			}
		}

		$this->data[$modelName]['__allows']['update'] = $this->{$modelName}->allowUpdate($tmp[$modelName]);
		$this->data[$modelName]['__allows']['delete'] = $this->{$modelName}->allowDelete($tmp[$modelName]);
		$this->set('tools_list', $this->{$modelName}->getModel('Test')->generateList());
		$this->set('client_id', $id);
	}

}

?>